package com.gh.reggie.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.reggie.common.BaseContext;
import com.gh.reggie.common.R;
import com.gh.reggie.entity.OrderDetail;
import com.gh.reggie.entity.Orders;
import com.gh.reggie.entity.ShoppingCart;
import com.gh.reggie.service.OrderDetailService;
import com.gh.reggie.service.OrdersService;
import com.gh.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.beancontext.BeanContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;




    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info(orders.toString());

        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page> page(int page,int pageSize){

        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Long userId = BaseContext.getCurrentId();
        //  select * from orders where userId = ? order by orderTime desc
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId).orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage,queryWrapper);
        return R.success(ordersPage);
    }

    private ServletRequest servletRequest;
    private String getRequestBody(HttpServletRequest request){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader reader = servletRequest.getReader();
            char [] buf = new char[1024];
            int length;
            while ((length = reader.read(buf)) != -1){
                stringBuilder.append(buf,0,length);
            }

        }catch (IOException e) {
            log.error("读取异常");
            throw new RuntimeException(e);
        }
        return stringBuilder.toString();
    }

    /**
     * 再来一单
     *
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders, HttpSession session){
        log.info(orders.toString());//orderID(订单号)
        Long user = (Long) session.getAttribute("user");
        log.info(user.toString());
        //1.根据订单id查询详细订单信息
        Orders order = ordersService.getOne(new LambdaQueryWrapper<Orders>().eq(Orders::getId,orders.getId()));
        String orderId = order.getNumber();
        List<OrderDetail> list = orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,orderId));
        Long userId = BaseContext.getCurrentId();
        //2.以流的形式添加每一份餐品到购物车
        List<ShoppingCart> shoppingCartList = list.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            //赋值orderDetail到shoppingCart
            BeanUtils.copyProperties(item, shoppingCart);
            //log.info("shoppingCart:{}", shoppingCart);//shoppingCart:ShoppingCart(id=1568512162989137922, name=口味蛇, image=0f4bd884-dc9c-4cf9-b59e-7d5958fec3dd.jpg, userId=null, dishId=1397851668262465537, setmealId=null, dishFlavor=少冰, number=1, amount=168.00, createTime=null)
            //设置userId
            shoppingCart.setUserId(userId);
            //设置createTime
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //log.info("shoppingCartList:{}", shoppingCartList);

        //先清空购物车  select * from shoppingCart where user_id = (session中存贮的id)
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(wrapper);
        //批量保存到购物车
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("订单以添加至购物车中");
    }



}
